package org.endy.leisure.diaTracker.service

import org.endy.leisure.diaTracker.entity.exam.AnswerPair
import org.endy.leisure.diaTracker.entity.exam.Exam
import org.endy.leisure.diaTracker.entity.exam.ExamAnswer
import org.endy.leisure.diaTracker.entity.exam.ExamListEntity
import org.endy.leisure.diaTracker.repository.ExamAnswerRepository
import org.endy.leisure.diaTracker.repository.ExamRepository
import org.springframework.stereotype.Service

@Service
class ExamService(private val examRepository: ExamRepository, private val examAnswerRepository: ExamAnswerRepository) {

    /**
     * 查询试卷列表
     */
    fun getExamList(userId: Long): List<ExamListEntity> {
        // 查询所有试卷
        val examList = examRepository.findAll()
        // 查询用户答题记录
        val examAnswerList = examAnswerRepository.findByUserId(userId)

        return examList.map { exam ->
            // 构建试卷答题列表
            val examEntity = ExamListEntity(
                id = exam.id!!,
                title = exam.title,
                paperPath = exam.paperPath,
                rightAnswer = exam.answer,
                paperType = exam.paperType
            )
            // 如果用户已经提交过答案，则将用户的答案变换为答案对比集添加到试卷中
            val answerPairList = examAnswerList?.findLast { answer ->
                answer.examId == exam.id
            }?.let {
                // 对比用户的答案
                val rightList = exam.answer.split(",")
                val userAnswerList = it.answer.split(",")
                rightList.zip(userAnswerList).map { (right, user) ->
                    val answerPair = if (right == user) {
                        AnswerPair(right, user, true)
                    } else {
                        AnswerPair(right, user, false)
                    }
                    answerPair
                }
            }
            examEntity.userAnswer = answerPairList
            examEntity
        }.toList()
    }

    /**
     * 提交试卷作答
     */
    fun submitExamAnswer(examAnswer: ExamAnswer) {
        // 检查是否已经提交过答题，如果没有提交则保存用户答案
        examAnswerRepository.findByExamIdAndUserId(examAnswer.examId, examAnswer.userId) ?: examAnswerRepository.save(
            examAnswer
        )
    }

    /**
     * 创建试卷信息
     */
    fun createExam(exam: Exam) {
        examRepository.save(exam)
    }

}